/* eslint-disable react-hooks/exhaustive-deps */
/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2024-01-13 16:00:13
 * @LastEditors: zhouhai zhouhaib@yonyou.com
 * @LastEditTime: 2024-10-23 17:56:10
 */
/* eslint-disable jsx-a11y/anchor-is-valid */
import {
    cleanOperlog,
    delOperLog,
    listOperLog,
} from '@/api/monitor/operLog';
import PageDiv from '@/components/PageDiv';
import ResizeTable from '@/components/ResizeTable';
import { useStore } from '@/store';
import { pageInfo } from '@/type.d/ajaxResult';
import { SysOperLogDomain } from '@/type.d/monitor/operLog';
import {
    ActionType,
    ProColumns,
    ProFormDateRangePicker,
    ProFormInstance,
    ProFormRadio,
    ProFormSelect,
    ProFormText,
    QueryFilter,
} from '@ant-design/pro-components';
import { Button, Modal, Space, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import SysOperLogCard from './operLogCard';

import { download } from '@/utils/request';
import { DeleteOutlined, DownloadOutlined } from '@ant-design/icons';
import './index.less';

const OperLog: React.FC = () => {
    const { layoutStore } = useStore();

    const actionRef = useRef<ActionType>();
    const queryformRef = useRef<ProFormInstance<SysOperLogDomain>>();
    const [queryValue, setQueryValue] = useState<SysOperLogDomain>({});
    const [tableListDataSource, setTableListDataSource] = useState<SysOperLogDomain[]>([]);

    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [pageInfo, setPageInfo] = useState<pageInfo>({
        current: 1,
        pageSize: 10,
        total: 0
    });

    const [cardData, setCardData] = useState<SysOperLogDomain>({});
    const [pageStatus, setPageStatus] = useState<'List' | 'Card'>('List');
    const [isedit, setIsedit] = useState<boolean>(false);


    const newdata = {}

    /**
     * 列表字段配置
     */
    const columns: ProColumns<SysOperLogDomain>[] = [
        {
            title: '日志编号',
            dataIndex: 'operId',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '系统模块',
            dataIndex: 'title',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '操作类型',
            dataIndex: 'businessType',
            valueType: 'select',
            align: 'left',
            width: '50',
            fieldProps: {
                options: [
                    { label: '其它', value: '0' },
                    { label: '新增', value: '1' },
                    { label: '修改', value: '2' },
                    { label: '删除', value: '3' },
                ]
            },
            render(dom, entity, index, action, schema) {
                let color = 'blue';
                switch (entity.businessType) {
                    case 0:
                        color = 'lime'
                        break;
                    case 1:
                        color = 'blue'
                        break;
                    case 2:
                        color = 'green'
                        break;
                    case 3:
                        color = 'red'
                        break;

                }
                return <Tag color={color}>{dom}</Tag>
            },
        },
        {
            title: '方法名称',
            dataIndex: 'method',
            valueType: 'text',
            align: 'left',
            width: '50',
            hideInTable: true
        },
        {
            title: '请求方式',
            dataIndex: 'requestMethod',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '操作类别',
            dataIndex: 'operatorType',
            valueType: 'select',
            align: 'left',
            width: '50',
            fieldProps: {
                options: [
                    { label: '其它', value: '0' },
                    { label: '后台用户', value: '1' },
                    { label: '手机端用户', value: '2' },
                ]
            },
        },
        {
            title: '操作人员',
            dataIndex: 'operName',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '部门名称',
            dataIndex: 'deptName',
            valueType: 'text',
            align: 'left',
            width: '50',
            hideInTable: true
        },
        {
            title: '请求URL',
            dataIndex: 'operUrl',
            valueType: 'text',
            align: 'left',
            width: '50',
            hideInTable: true
        },
        {
            title: '主机地址',
            dataIndex: 'operIp',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '操作地点',
            dataIndex: 'operLocation',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '请求参数',
            dataIndex: 'operParam',
            hideInTable: true
        },
        {
            title: '返回参数',
            dataIndex: 'jsonResult',
            hideInTable: true
        },
        {
            title: '操作状态',
            dataIndex: 'status',
            valueType: 'radio',
            align: 'left',
            width: '50',
            fieldProps: {
                options: [
                    { label: '正常', value: '0' },
                    { label: '异常', value: '1' },
                ],
            },
            render(dom, entity, index, action, schema) {
                const color = entity.status === 0 ? 'blue' : 'red';
                return <Tag color={color}>{dom}</Tag>
            },
        },
        {
            title: '错误消息',
            dataIndex: 'errorMsg',
            hideInTable: true
        },
        {
            title: '操作时间',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            align: 'left',
            width: '50',
        },
        {
            title: '备注',
            dataIndex: 'remark',
        },
        {
            title: '操作',
            width: 180,
            key: 'option',
            valueType: 'option',
            render: (_dom: React.ReactNode, entity: SysOperLogDomain) => [
                <a key="view" onClick={() => {
                    onView(entity)
                }}>详情</a>
            ],
        },
    ];

    const toCard = (data: SysOperLogDomain, isEdit: boolean = false) => {
        setQueryValue(queryformRef.current?.getFieldsValue() || {})
        setPageStatus('Card')
        setCardData({ ...data })
        setIsedit(isEdit)
    }

    const onView = (data: SysOperLogDomain) => {
        toCard(data)
    }


    const onDelete = () => {
        if (selectedRowKeys && selectedRowKeys.length > 0) {
            layoutStore.OpenSpanning()
            delOperLog(selectedRowKeys.join(',')).then(() => {
                const _data = queryformRef?.current?.getFieldsValue()
                onQuery({ ...pageInfo, ..._data })
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }

    const onClearn = () => {
        layoutStore.OpenSpanning()
        cleanOperlog().then(() => {
            setSelectedRowKeys([]);
            setTableListDataSource([])
        }).finally(() => {
            layoutStore.CloseSpanning()
        })
    }


    const onExport = () => {
        layoutStore.OpenSpanning()
        download('/monitor/operLog/export', queryformRef?.current?.getFieldsValue(), `operlog_${new Date().getTime()}.xlsx`)
        layoutStore.CloseSpanning()
    }
    const headButton = () => {
        return <Space>
            <Button
                icon={<DeleteOutlined />}
                key="delete"
                type="primary"
                onClick={() => Modal.confirm({
                    title: '警告',
                    content: '确定要删除选中的操作日志吗？',
                    onOk: onDelete
                })}
            >
                删除
            </Button>
            <Button
                icon={<DeleteOutlined />}
                key="clearn"
                type="primary"
                onClick={() => Modal.confirm({
                    title: '警告',
                    content: '确定要清空所有的操作日志吗？',
                    onOk: onClearn
                })}
            >
                清空
            </Button>
            <Button
                icon={<DownloadOutlined />}
                key="export"
                type="primary"
                onClick={onExport}
            >
                导出
            </Button>
        </Space >
    }

    //监听分页得操作
    useEffect(() => {
        if (pageInfo.total > 0) {
            //如果原页面有数据，触发查询
            const _data = queryformRef?.current?.getFieldsValue()
            onQuery({...pageInfo,..._data})
        }
    }, [pageInfo.current,pageInfo.pageSize])


    const onQuery = async (_data: any) => {
        if (_data.operTime) {
            _data.params = {}
            _data.params['beginTime'] = _data.operTime[0];
            _data.params['endTime'] = _data.operTime[1];
            delete _data.operTime
        }

        layoutStore.OpenSpanning();
        listOperLog(_data).then((res) => {
            setSelectedRowKeys([]);
            setTableListDataSource(res.data)
            if (res.total) {
                setPageInfo({ ...pageInfo, total: res.total })
            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })

        return _data;
    }

    const onPageChange: (current: number, pageSize: number) => void = (current, pageSize) => {
        setPageInfo({ ...pageInfo, current, pageSize });
    };

    useEffect(() => {
        if (pageStatus === 'List') {
            queryformRef.current?.setFieldsValue(queryValue)
        }
    }, [pageStatus])

    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };


    return (
        <PageDiv>{
            pageStatus === 'List' ? <PageDiv>
                <QueryFilter<SysOperLogDomain>
                    defaultCollapsed
                    split
                    span={4}
                    onFinish={(_data) => onQuery({ ...pageInfo, ..._data, current: 1, })}
                    formRef={queryformRef}>
                    <ProFormText key='title' name="title" label="系统模块" />
                    <ProFormText key='operName' name="operName" label="操作人员" />
                    <ProFormSelect key='businessType' name="businessType"
                        label="操作类型" options={[
                            { label: '其它', value: '0' },
                            { label: '新增', value: '1' },
                            { label: '修改', value: '2' },
                            { label: '删除', value: '3' },
                        ]}
                    />
                    <ProFormRadio.Group key='status' name="status" label="操作状态"
                        options={[
                            { label: '正常', value: '0' },
                            { label: '异常', value: '1' },
                        ]}
                    />
                    <ProFormDateRangePicker key='operTime' name="operTime" label="操作时间" />

                    <ProFormText key='method' name="method" label="方法名称" hidden />

                    <ProFormText key='requestMethod' name="requestMethod" label="请求方式" hidden />

                    <ProFormSelect key='operatorType' name="operatorType" label="操作类别" hidden
                        options={[
                            { label: '其它', value: '0' },
                            { label: '后台用户', value: '1' },
                            { label: '手机端用户', value: '2' },]} />


                    <ProFormText key='operUrl' name="operUrl" label="请求URL" hidden />

                    <ProFormText key='operIp' name="operIp" label="主机地址" hidden />

                    <ProFormText key='operLocation' name="operLocation" label="操作地点" hidden />

                </QueryFilter>
                <ResizeTable<SysOperLogDomain>
                    rowKey={'operId'}
                    onRow={record => {
                        return {
                            onDoubleClick: event => {
                                onView(record)
                            },
                        };
                    }}
                    dataSource={tableListDataSource}
                    actionRef={actionRef}
                    columns={columns}
                    cardBordered
                    revalidateOnFocus={false}
                    pagination={{
                        ...pageInfo,
                        showTitle: false,
                        onChange: onPageChange
                    }}
                    headerTitle={headButton()}
                    rowSelection={rowSelection}
                >
                </ResizeTable>
            </PageDiv> :
                <SysOperLogCard
                    onBack={() => setPageStatus('List')}
                    isedit={isedit}
                    setIsedit={setIsedit}
                    cardData={cardData}
                    newdata={newdata}
                    tableListDataSource={tableListDataSource}
                    setTableListDataSource={setTableListDataSource} />}
        </PageDiv>

    )
}
export default OperLog;